package org.flower.web.servlet;

import com.alibaba.fastjson.JSON;
import org.flower.dao.CommodityDetailsDao;
import org.flower.dao.OrderDao;
import org.flower.dao.OrderDetailsDao;
import org.flower.dao.ShoppingCartDao;
import org.flower.dao.impl.CommodityDetailsDaoImpl;
import org.flower.dao.impl.OrderDaoImpl;
import org.flower.dao.impl.OrderDetailsDaoImpl;
import org.flower.dao.impl.ShoppingCartDaoImpl;
import org.flower.entity.Order;
import org.flower.entity.OrderDetails;
import org.flower.entity.ShoppingCart;
import org.flower.entity.User;
import org.flower.utils.MyStringUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//购物车
@WebServlet(urlPatterns = "/user/shoppingCart.shtml")
public class shoppingCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取登录的该用户
        User u = (User)request.getSession().getAttribute("user");
        //查询该用户的购物车信息
        ShoppingCartDao shdao = new ShoppingCartDaoImpl();
        List<ShoppingCart> userShoppingCart = shdao.getShoppingAllByUid(u.getId());
        //获取用户的购物车数量
        int cartNum =  shdao.getShoppingCountNum(u.getId());
        //将session中的商品数量 更新
        request.getSession().setAttribute("userShoppingCartNum",cartNum);
        //计算总价钱
        double totalPrice = 0;
        //被勾选商品的总价钱
        double activePrice = 0;
        for(ShoppingCart cart : userShoppingCart){
            //获取商品价格
            double price = cart.getCommodity().getOutPrice();
            //获取商品个数
            double num = cart.getNum();
            double sum = price*num;
            totalPrice += sum;
            //判断该商品是不是勾选状态
            if(cart.isFlag()){
                activePrice += sum;
            }
        }
        //将数据保存到request作用域中
        request.setAttribute("userShoppingCart",userShoppingCart);
        request.setAttribute("cartNum",cartNum);
        request.setAttribute("totalPrice",totalPrice);
        request.setAttribute("activePrice",activePrice);
        //页面转发
        request.getRequestDispatcher("shoppingTrolley2.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        ShoppingCartDao shdao = new ShoppingCartDaoImpl();
        //获取等录的用户信息
        User u = (User)request.getSession().getAttribute("user");
        //获取参数
        String flag = request.getParameter("flag");
        //获取购物车编号
        String id = request.getParameter("id");
        switch (flag){
            case "switchState":
                //切换商品的勾选状态
                //执行修改购物车勾选状态并返回
                out.print(shdao.updateShoppingFlag(Integer.parseInt(id)));
                break;
            case "jia":
                //点击加号 更改购物车数量 并返回
                out.print(shdao.updateShoppingNum1(Integer.parseInt(id),1));
                break;
            case "jian":
                //点击减号 更改购物车数量 并返回
                out.print(shdao.updateShoppingNum1(Integer.parseInt(id),-1));
                break;
            case "delete":
                //点击删除 删除该条信息 并返回
                boolean delfalg = shdao.delShoppingById(Integer.parseInt(id));
                //更新 用户的购物车数量
                request.getSession().setAttribute("userShoppingCartNum",shdao.getShoppingCountNum(u.getId()));
                out.print(delfalg);
                break;
            case "inputController":
                //文本框数据改变数量
                //获取 数量
                String num = request.getParameter("num");
                out.print(shdao.updateShoppingNumInput(Integer.parseInt(id),Integer.parseInt(num)));
                break;
            case "ChangeActive":
                //查询购物车 是否至少有一个被勾选
                List<ShoppingCart> shoppingList = shdao.getShoppingAllByUid(u.getId());
                boolean  active = false;
                for(ShoppingCart sh : shoppingList){
                    if(sh.isFlag()){
                        active = true;
                        break;
                    }
                }
                out.print(active);
                break;
            case "selectKucun":
                //获取用户的编号
                List<ShoppingCart> shoppingList2 = shdao.getShoppingAllByUid(u.getId());
                CommodityDetailsDao comdao = new CommodityDetailsDaoImpl();
                //查询商品的数量是否大于库存数量
                String str = "";
                for(ShoppingCart sh : shoppingList2){
                    if(sh.isFlag()){
                        //获取该商品的库存数量做判断
                        int stock = comdao.getCommodityStockdById(sh.getComDetailsId());
                        if(sh.getNum()>stock){
                            str = comdao.getCommodityNameById(sh.getComDetailsId());
                            break;
                        }
                    }
                }
                out.print(str);
                break;
            case "selectActive":
                //查询购物车是勾选状态的 信息
                List<ShoppingCart> shoppingListChanged = shdao.getShoppingAllAndYesChangedByUid(u.getId());
                out.print(JSON.toJSONString(shoppingListChanged));
                break;
            case "addOrder":
                //添加购物车
                //查询购物车中的所有勾选的商品信息
                List<ShoppingCart> shoppingLists =  shdao.getShoppingAllAndYesChangedByUid(u.getId());
                if(shoppingLists.size()<=0){
                    //没有商品可添加 订单生成失败
                    out.print(false);
                    return;
                }
                OrderDetails orderdetails = new OrderDetails();
                OrderDetailsDao oddao = new OrderDetailsDaoImpl();
                //获取订单编号

                CommodityDetailsDao cdd = new CommodityDetailsDaoImpl();

                String orderId = MyStringUtil.getOrderId();
                double sumPrice=0;
                //首先添加订单详情 然后添加订单
                for(ShoppingCart s : shoppingLists){
                    orderdetails.setOrderId(orderId);
                    orderdetails.setComdetailsId(s.getComDetailsId());
                    orderdetails.setNum(s.getNum());


                    orderdetails.setTotalPrice(s.getNum()*s.getCommodity().getOutPrice());
//                    sumPrice += orderdetails.getTotalPrice() * s.getNum();
                    //执行订单详情的添加
                    if(oddao.addOrderDetails(orderdetails)){
                        //减少库存
                        cdd.upataStockdById(s.getComDetailsId(),-s.getNum());
                        //添加销量
                        cdd.updateOutNumber(s.getComDetailsId(),s.getNum());
                        //将商品信息 添加到 订单详情中 删除购物车中的商品信息
                        shdao.delShoppingById(s.getId());
                    }else{
                        out.print(false);
                        return;
                    }
                }
                //更新 用户的购物车数量
                request.getSession().setAttribute("userShoppingCartNum",shdao.getShoppingCountNum(u.getId()));
                //获取参数
                String shouName = request.getParameter("shouName");
                String shouPhone = request.getParameter("shouPhone");
                String shouAddress = request.getParameter("shouAddress");
                String dingName = request.getParameter("dingName");
                String dingPhone = request.getParameter("dingPhone");
                String date = request.getParameter("date");
                String liuYan = request.getParameter("liuYan");
                String beizhu = request.getParameter("beizhu");
                String yingfu = request.getParameter("yingfu");
                String shifu = request.getParameter("shifu");

                //送达日期 类型转换
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date songDaDate = new Date();
                try {
                    songDaDate = sdf.parse(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                /** 封装订单对象
                 编号 收获人姓名 收获手机号 收获地址 订货人姓名 订货手机号
                 送达日期 贺卡留言 备注	*购物券编号* 应付金额 实付金额 订单状态 用户编号
                 */
                Order o = new Order();
                o.setId(orderId);
                o.setShouName(shouName);
                o.setShouPhone(shouPhone);
                o.setShouAddress(shouAddress);
                o.setDingPhone(dingPhone);
                o.setDingName(dingName);
                o.setCouId("0");
                o.setServiceDate(songDaDate);
                o.setGreetingCardMsg(liuYan);
                o.setContent(beizhu);
                o.setCopewithPrice(Double.parseDouble(yingfu));
                o.setPaidinPrice(Double.parseDouble(shifu));
                o.setUserId(u.getId());
                o.setOrderState(1);
                //将信息存入到session
                request.getSession().setAttribute("orderId",o.getId());
                request.getSession().setAttribute("shifu",o.getPaidinPrice());
                //开始添加订单
                OrderDao odao = new OrderDaoImpl();
                out.print(odao.addOrder(o));
                break;
            case "updateOrderState":
                //获取订单号
                String orderid = request.getParameter("orderid");
                //将该订单状态改成 已付款
                OrderDao odao2 = new OrderDaoImpl();
                out.print(odao2.updateOrderStateById(orderid,2));
                break;
            default:
                out.print(false);
                break;
        }
    }
}
